package org.mwt.ws.webclient.business;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

public class XmlRpcService implements RemoteService {

    public String CreateXForm(String statement) throws BusinessException {
        String result = "";
        try {
            result = executeCall(statement, "CreateXForm");
            System.out.println("XMLRPC-LOG: Result = "+result);
            return result;
        } catch (Exception ex) {
            Logger.getLogger(XmlRpcService.class.getName()).log(Level.SEVERE, null, ex);
            throw new BusinessException("Errore durante la chiamata XML-RPC CreateXForm", ex);
        }
    }

    public String CreateInsertCode(String statement) throws BusinessException {
        String result = "";
        try {
            result = executeCall(statement, "CreateInsertCode");
            System.out.println("XMLRPC-LOG: Result = "+result);
            return result;
        } catch (Exception ex) {
            Logger.getLogger(XmlRpcService.class.getName()).log(Level.SEVERE, null, ex);
            throw new BusinessException("Errore durante la chiamata XML-RPC CreateXForm", ex);
        }
    }

    public String CreateUpdateCode(String statement) throws BusinessException {
        String result = "";
        try {
            result = executeCall(statement, "CreateUpdateCode");
            System.out.println("XMLRPC-LOG: Result = "+result);
            return result;
        } catch (Exception ex) {
            Logger.getLogger(XmlRpcService.class.getName()).log(Level.SEVERE, null, ex);
            throw new BusinessException("Errore durante la chiamata XML-RPC CreateXForm", ex);
        }
    }

    private String executeCall(String statement, String action) throws MalformedURLException, XmlRpcException {
        XmlRpcClientConfigImpl c = new XmlRpcClientConfigImpl();
        c.setServerURL(new URL("http://127.0.0.1:8080/ServerXDBForms/xmlrpc"));

        XmlRpcClient client = new XmlRpcClient();
        client.setConfig(c);

        Object[] params = new Object[1];
        params[0] = statement;

        return (String) client.execute("XmlRpcXDBForms."+action, params);
    }
}
